/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.saber.certificacao.beansjsf.principal;

import br.com.saber.certificacao.beansjsf.interfacebean.BeanJSFInterface;
import br.com.saber.certificacao.ejbs.stateless.interfaces.SaberDTOBeanLocal;
import br.com.saber.certificacao.modelos.Usuario;
import br.com.saber.certificacao.modelos.dto.VersaoMotherDTO;
import br.com.saber.certificacao.observador.ControleObserver;
import br.com.saber.certificacao.utils.ParametrosContexto;
import br.com.saber.certificacao.utils.UtilMetodos;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ApplicationScoped;
import java.util.Observer;
import javax.faces.context.FacesContext;
import org.apache.commons.lang.StringUtils;
import org.primefaces.model.chart.CartesianChartModel;
import org.primefaces.model.chart.ChartSeries;

/**
 *
 * @author gbvbahia
 */
@ManagedBean(name = "questoesSaberManager")
@ApplicationScoped
public class QuestoesSaberManager implements BeanJSFInterface, Observer {

    @EJB
    private SaberDTOBeanLocal saberDTOBean;
    private List<PieInfo> pieModel;

    public QuestoesSaberManager() {
    }

    //====================
    // Iniciadores
    //====================
    @Override
    @PostConstruct
    public void init() {
        Usuario userAppl = new Usuario();
        userAppl.setId(ControleObserver.id);
        ControleObserver.addBeanObserver(userAppl, this);
        Logger.getLogger(this.getClass().getName()).log(Level.FINEST, "QuestoesSaberManager.init() executado!");
    }

    @Override
    @PreDestroy
    public void end() {
        Usuario userAppl = new Usuario();
        userAppl.setId(ControleObserver.id);
        Logger.getLogger(this.getClass().getName()).log(Level.FINEST, "QuestoesSaberManager.end() executado!");
    }

    //====================
    //Métodos de Negócio
    //====================
    @Override
    public void update(Observable o, Object arg) {
        String[] args = (String[]) arg;
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals(ControleObserver.Eventos.CAD_QUESTAO_EVENT) || args[i].equals(ControleObserver.Eventos.BLOQ_QUESTAO_EVENT)) {
                atualizarQuestoes();
            }
        }
    }

    private void atualizarQuestoes() {
        List<VersaoMotherDTO> dtos = this.saberDTOBean.buscarTodosVersaoMotherDTO(true);
        this.pieModel = new ArrayList<PieInfo>();
        for (VersaoMotherDTO dto : dtos) {
            PieInfo pi = new PieInfo();
            pi.setTitleVersao(dto.getVersaoMotherNome());
            pi.setTitleCertificacao(dto.getCertificacaoNome());
            pi.setUrl(dto.getUrl());
            CartesianChartModel pie = new CartesianChartModel();
            ChartSeries questoesPortugues = new ChartSeries();
            ChartSeries questoesIngles = new ChartSeries();
            questoesPortugues.setLabel(UtilMetodos.getResourceBundle("labelBarrQuestoesPortugues", FacesContext.getCurrentInstance()));
            questoesIngles.setLabel(UtilMetodos.getResourceBundle("labelBarrQuestoesIngles", FacesContext.getCurrentInstance()));
            int altura = 0;
            int total = 0;
            for (String obj : dto.getObjetivoQuantidade().keySet()) {
                int por = dto.getObjetivoQuantidade().get(obj)[0];
                int ing = dto.getObjetivoQuantidade().get(obj)[1];
                questoesPortugues.set(StringUtils.substring(obj, 0, 15), por);
                questoesIngles.set(StringUtils.substring(obj, 0, 15), ing);
                if (altura < por + ing) {
                    altura = ing + por;
                    pi.setAltura(altura + 1);
                }
                total += por + ing;
            }
            if (total >= Integer.parseInt(ParametrosContexto.getParameterContexto(ParametrosContexto.QUANTIDADE_MINIMA_QUESTOES_CERTIFICACAO, FacesContext.getCurrentInstance()))) {
                pie.addSeries(questoesPortugues);
                pie.addSeries(questoesIngles);
                pi.setCategoryModel(pie);
                pi.setTotalQuestoes(total);
                this.pieModel.add(pi);
            }
        }
    }

    //====================
    //Table Actions
    //====================
    //====================
    //SelectItem
    //====================
    //=========================
    //Getters AND Setters
    //=========================
    public List<PieInfo> getPieModel() {
        if (this.pieModel == null) {
            atualizarQuestoes();
        }
        return pieModel;
    }

    public void setPieModel(List<PieInfo> pieModel) {
        this.pieModel = pieModel;
    }

    //=========================
    //INNER CLASS
    //=========================
    public class PieInfo {

        private CartesianChartModel categoryModel;
        ;
        private String titleVersao;
        private String titleCertificacao;
        private String url;
        private int totalQuestoes;
        private int altura;

        public CartesianChartModel getCategoryModel() {
            return categoryModel;
        }

        public void setCategoryModel(CartesianChartModel categoryModel) {
            this.categoryModel = categoryModel;
        }

        public String getTitleCertificacao() {
            return titleCertificacao;
        }

        public void setTitleCertificacao(String titleCertificacao) {
            this.titleCertificacao = titleCertificacao;
        }

        public String getTitleVersao() {
            return titleVersao;
        }

        public void setTitleVersao(String titleVersao) {
            this.titleVersao = titleVersao;
        }

        public int getAltura() {
            return altura;
        }

        public void setAltura(int altura) {
            this.altura = altura;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public int getTotalQuestoes() {
            return totalQuestoes;
        }

        public void setTotalQuestoes(int totalQuestoes) {
            this.totalQuestoes = totalQuestoes;
        }
    }
}
